package org.ponly.lpf4j.web;

import org.ponly.web.servlet.ProxiedFilterChain;

import javax.servlet.*;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 */
// extension point
class PluginServletFilter implements Filter {
    private final List<Filter> filters = new CopyOnWriteArrayList<Filter>();
    private FilterConfig config;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
        this.config.getServletContext().setAttribute("", this);

        for (Filter filter : filters) {
            filter.init(config);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        getProxiedFilterChain(chain, filters).doFilter(request, response);
    }

    protected FilterChain getProxiedFilterChain(FilterChain orig, List<Filter> filters) {
        return new ProxiedFilterChain(orig, filters);
    }

    @Override
    public void destroy() {
        for (int i = filters.size(); i > 0; i--) {
            filters.get(i).destroy();
        }
        filters.clear();
    }
}
